package com.tsinghuabigdata.edu.ddmath;

import android.content.ComponentCallbacks2;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.multidex.MultiDexApplication;
import android.text.TextUtils;

import com.mobsandgeeks.saripaar.Validator;
import com.squareup.picasso.OkHttpDownloader;
import com.squareup.picasso.Picasso;
import com.tsinghuabigdata.edu.commons.cache.AppCache;
import com.tsinghuabigdata.edu.commons.cache.CacheManager;
import com.tsinghuabigdata.edu.ddmath.bean.LoginInfo;
import com.tsinghuabigdata.edu.ddmath.commons.AppSessionCache;
import com.tsinghuabigdata.edu.ddmath.commons.CrashHandler;
import com.tsinghuabigdata.edu.ddmath.commons.http.AppRequestUtils;
import com.tsinghuabigdata.edu.ddmath.commons.http.InformMapping;
import com.tsinghuabigdata.edu.ddmath.commons.validate.MobileValidateCode;
import com.tsinghuabigdata.edu.ddmath.constant.AppConst;
import com.tsinghuabigdata.edu.ddmath.constant.BaseConfig;
import com.tsinghuabigdata.edu.ddmath.constant.ErrTag;
import com.tsinghuabigdata.edu.ddmath.module.ddwork.DDWorkUtil;
import com.tsinghuabigdata.edu.ddmath.requestHandler.MyLearnService;
import com.tsinghuabigdata.edu.ddmath.requestHandler.RoboGuiceModule;
import com.tsinghuabigdata.edu.ddmath.requestHandler.requestImpl.MyLearnServiceImpl;
import com.tsinghuabigdata.edu.ddmath.util.AccountUtils;
import com.tsinghuabigdata.edu.ddmath.util.AppLog;
import com.tsinghuabigdata.edu.ddmath.util.AppUtils;
import com.tsinghuabigdata.edu.ddmath.util.DirUtils;
import com.tsinghuabigdata.edu.utils.NetworkUtils;

import org.xutils.x;

import java.io.File;
import java.io.IOException;

import roboguice.RoboGuice;

//import com.tsinghuabigdata.edu.ddmath.receive.ShutdownReceiver;
//import com.tsinghuabigdata.edu.ddmath.bean.LoginInfo;

public class ZxApplication extends MultiDexApplication {

    public static final String LOG_TAG = "ddmath";
    //统计Activity start stop的次数  == 0 进入后台，>0 在前台
    private static int stateCount = 0;
    private static MyLearnService myLearnService;

    private static ZxApplication application;

    //private UserBehavior userBehavior;
    //private BroadcastReceiver receiver;


    public static ZxApplication getApplication() {
        return application;
    }

    private static void settApplication(ZxApplication application) {
        ZxApplication.application = application;
    }

    public static MyLearnService getLearnService() {
        return myLearnService;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        myLearnService = new MyLearnServiceImpl();

        NetworkUtils.init(this);

        // 初始化Crash日志采集
        CrashHandler crashHandler = CrashHandler.getInstance();
        crashHandler.init(getApplicationContext(), this);

        // 不使用注解
        RoboGuice.setUseAnnotationDatabases(false);

        // 设置注入模块
        RoboGuice.overrideApplicationInjector(this, new RoboGuiceModule());

        // 注册自定义验证
        Validator.registerAnnotation(MobileValidateCode.class);

        // 接口类初始化
        AppRequestUtils.initialization(this);

        // 初始化映射
        InformMapping.initialization(this);

        ZxApplication.settApplication(this);

        DDWorkUtil.init( this );        //初始化题型数据

        //初始化xutils注解
        x.Ext.init(this);
        x.Ext.setDebug(BuildConfig.DEBUG);

        int appVersion = 1;
        try {
            // 获取当前的版本号
            PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0);
            appVersion = info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            AppLog.i("PackageInfo", "getPackageManager err", e);
        }
        // 初始缓存类
        CacheManager.init(new File(DirUtils.getExternalDir(AppConst.IMAGE_CACHE_DIR)), appVersion);
        // 初始化本地缓存
        try {
            // 相对与sdcard/Android/data/{package}/cache/obj/
            AppSessionCache.init(new File(DirUtils.getExternalPrivateFileDir(this, AppConst.OBJECT_CACHE_DIR)), appVersion);
        } catch (IOException e) {
            AppLog.i(ErrTag.TAG_IO, "init err", e);
            //onTerminate();
            //android.os.Process.killProcess(android.os.Process.myPid());    //获取PID
        }
        //网易云初始化
        NeteaseImApplication.init(this);

        final String imageCacheDir = getExternalCacheDir() + "/cache_image";
        Picasso picasso = new Picasso.Builder(this).downloader( new OkHttpDownloader(new File(imageCacheDir))).build();
        Picasso.setSingletonInstance(picasso);

        // 初始化日志
        String sessionid = "";
        //String tokenid = "";
        LoginInfo loginInfo = AccountUtils.getLoginUser();
        if (loginInfo != null) {
            sessionid = loginInfo.getAccountId();
            //tokenid = loginInfo.getAccessToken();
        }
        if (TextUtils.isEmpty(sessionid)) {
            sessionid = AppUtils.getDeviceId(this);
        }
        String appver = "";
        PackageInfo info = AppUtils.getPackageInfo(this);
        if (info != null) {
            appver = info.versionName;
        }
        AppLog.configLog4j(this, sessionid, "DDMATH_STUDENT_ANDROID", BaseConfig.LOG_SERVER, appver);

//        Stetho.initialize(
//                Stetho.newInitializerBuilder(this)
//                        .enableDumpapp(Stetho.defaultDumperPluginsProvider(this))
//                        .enableWebKitInspector(Stetho.defaultInspectorModulesProvider(this))
//                        .build());
//        userBehavior = new UserBehavior();
//
//        //注册用户行为统计功能
//        registerActivityLifecycleCallbacks(userBehavior);
//        BehaviorUtil behaviorUtil = BehaviorUtil.instance();
//        behaviorUtil.config(this, "2B2C_STUDENT_ANDROID", tokenid, AppConfig.UPLOAD_HOST);

        //关机广播监听
        //com.tsinghuabigdata.edu.ddmath.receive.ShutdownReceiver.register(this);

    }

    @Override
    public void onTerminate() {
        clear();
        //unRegisterReceiver();
        //unregisterActivityLifecycleCallbacks(userBehavior);
        //ShutdownReceiver.unRegister(this);

        super.onTerminate();

//        android.os.Process.killProcess(android.os.Process.myPid());    //获取PID
//        System.exit(0);   //常规java、c#的标准退出法，返回值为0代表正常退出
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        if (level >= ComponentCallbacks2.TRIM_MEMORY_MODERATE) {
            // Clear the caches.  Note all pending requests will be removed too.
            clear();
        }
    }

//    Handler mHandler = new Handler(){
//        @Override
//        public void handleMessage(Message msg){
//            if( msg.what == 0 && msg.obj instanceof String ){
//                String data = (String)msg.obj;
//                ToastUtils.showPoint( getBaseContext(), data );
//            }
//        }
//    };
//    public void showToast( String data ){
//        mHandler.removeMessages( 0 );
//        Message msg = new Message();
//        msg.what = 0;
//        msg.obj = data;
//        mHandler.sendMessage( msg );
//    }


    public synchronized static void addStatCount() {
        stateCount++;
    }

    public synchronized static void decStatCount() {
        stateCount--;
    }

    //
//    class UserBehavior implements ActivityLifecycleCallbacks {
//        private static final String STATE_ENTER = "enter";
//        private static final String STATE_QUIT = "quit";
//        private String state = "";
//
//        @Override
//        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
//            //Log.e("UserBehavior"," onActivityCreated activity = " + activity.getLocalClassName() );
//        }
//
//        @Override
//        public void onActivityStarted(Activity activity) {
////            Log.e("UserBehavior", " onActivityStarted activity = " + activity.getLocalClassName());
//            if (!activity.getLocalClassName().equals("android.activity.LoginActivity")) {
//                addStatCount();
//                if (stateCount != 0) {
//                    if (!state.equals(STATE_ENTER)) {
//                        state = STATE_ENTER;
//                        //BehaviorUtil.enterApp();
//                        //Log.e("UserBehavior", " enter");
//                    }
//                }
//            }
//            //Log.e("UserBehavior", "onActivityStarted: " + stateCount);
//        }
//
//        @Override
//        public void onActivityResumed(Activity activity) {
////            Log.e("UserBehavior", " onActivityResumed activity = " + activity.getLocalClassName());
//        }
//
//        @Override
//        public void onActivityPaused(Activity activity) {
////            Log.e("UserBehavior", " onActivityPaused activity = " + activity.getLocalClassName());
//        }
//
//        @Override
//        public void onActivityStopped(Activity activity) {
////            Log.e("UserBehavior", " onActivityStopped activity = " + activity.getLocalClassName());
//            if (!activity.getLocalClassName().equals("android.activity.LoginActivity")) {
//                decStatCount();
//                if (stateCount == 0) {   //退出App
//                    state = STATE_QUIT;
//                    //BehaviorUtil.quitApp();
//                    //Log.e("UserBehavior", " quit");
//                }
//            }
//            //Log.e("UserBehavior", "onActivityStopped: " + stateCount);
//        }
//
//        @Override
//        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
////            Log.e("UserBehavior", " onActivitySaveInstanceState activity = " + activity.getLocalClassName());
//        }
//
//        @Override
//        public void onActivityDestroyed(Activity activity) {
//            //Log.e("UserBehavior", " onActivityDestroyed activity = " + activity.getLocalClassName());
//        }
//    }


    private void clear() {
        AppCache.getInstance().evictAll();
    }

//    private void registerReceiver() {
//        registerReceiver(receiver, new IntentFilter("NSPenBroadcastRecevie.NsRequest"));
//    }
//
//    private void unRegisterReceiver() {
//        unregisterReceiver(receiver);
//    }

}
